// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"sync"
	"time"
)

const (
	_CFG_KEY         = "cfg"
	_LOAD_TIME_KEY   = "loadTime"
	_CHANGE_TIME_KEY = "changeTime"
)

var _cacheMap *sync.Map

func ReadServerConfigFromCache() (*ServerConfig, error) {
	needLoad := false
	loadTime, _ := _cacheMap.Load(_LOAD_TIME_KEY)
	changeTime, _ := _cacheMap.Load(_CHANGE_TIME_KEY)
	if loadTime.(int64) < changeTime.(int64) {
		needLoad = true
	}
	if !needLoad {
		cfg, ok := _cacheMap.Load(_CFG_KEY)
		if ok {
			return cfg.(*ServerConfig), nil
		}
	}
	cfg, err := ReadServerConfig()
	if err != nil {
		return nil, err
	}
	nowTime := time.Now().UnixMilli()
	_cacheMap.Store(_CFG_KEY, cfg)
	_cacheMap.Store(_LOAD_TIME_KEY, nowTime)
	return cfg, nil
}

func MarkServerConfigChange() {
	nowTime := time.Now().UnixMilli()
	_cacheMap.Store(_CHANGE_TIME_KEY, nowTime)
}

func init() {
	_cacheMap = &sync.Map{}
	_cacheMap.Store(_LOAD_TIME_KEY, int64(0))
	_cacheMap.Store(_CHANGE_TIME_KEY, int64(0))
}
